package main

import (
	utils "cmd-tools/common"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

const TIME_FORMAT = "2006-01-02 15:04:05"

func GetArgs(i int, defVal string) string {
	if i >= len(os.Args) {
		return defVal
	} else {
		return os.Args[i]
	}
}

func main() {
	myArgs := new(utils.MyArgs)
	f := myArgs.GetByIndex(1, "")
	v := myArgs.GetByIndex(2, "")
	ln := myArgs.GetByIndex(3, "Asia/Chongqing")

	if f != "" && f != "-d" && f != "-s" {
		fmt.Println(`
mydate命令可以获取当前时间或指定时间的格式化时间或时间戳
mydate [-d/-s] [value] [locationName]
-d 日期时间格式输出yyyy-MM-dd HH:mm:ss
-s 时间戳输出
value 指定时间，缺省时为当前系统时间
locationName 指定时区，默认“Asia/Chongqing”，仅-d时有用
例：
mydate //返回当前时间
mydate -s //返回当前时间戳
		`)
		return
	}

	var vTime time.Time
	if v == "" {
		vTime = time.Now()
	} else if strings.Contains(v, "-") {
		n := len(v)
		if 19 < n {
			return
		}
		if n < 19 {
			v = v + "2022-01-01 00:00:00"[n:19]
		}
		l, err := time.LoadLocation(ln)
		if nil != err {
			fmt.Println(err.Error(), "输入为："+ln)
			return
		}
		vTime, _ = time.ParseInLocation(TIME_FORMAT, v, l)
	} else {
		_s, err := strconv.ParseInt(v, 10, 64)
		if nil != err {
			fmt.Println(err.Error(), "输入为："+v)
			return
		}
		vTime = time.Unix(_s, 0)
	}

	if f == "" || f == "-d" {
		fmt.Println(vTime.Format(TIME_FORMAT))
	} else if f == "-s" {
		fmt.Println(vTime.Unix())
	}
}
